package com.zhiche.lisa.integration.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.enums.IntegrationURIEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.integration.dao.model.ExportLog;
import com.zhiche.lisa.integration.dao.model.ExportLogHistory;
import com.zhiche.lisa.integration.dao.model.PushSubSystem;
import com.zhiche.lisa.integration.service.IBMSService;
import com.zhiche.lisa.integration.service.IExportLogHistoryService;
import com.zhiche.lisa.integration.service.IExportLogService;
import com.zhiche.lisa.integration.service.IPushSubSystemService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class BMSServiceImpl implements IBMSService {

    @Autowired
    private IPushSubSystemService subSystemService;
    @Autowired
    private IExportLogService exportLogService;
    @Autowired
    private IExportLogHistoryService exportLogHistoryService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * bms查询标准价格和里程
     */
    @Override
    public JSONObject getPriceAndMiles(Map<String, String> condition) {
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        if (StringUtils.isBlank(condition.get("orderno"))) {
            throw new BaseException("订单号不能为空");
        }
        //发送请求
        EntityWrapper<PushSubSystem> ew = new EntityWrapper<>();
        ew.eq("type", IntegrationURIEnum.OTM_PRICE_MILES.getCode())
                .orderBy("id", false);
        PushSubSystem subSystem = subSystemService.selectOne(ew);
        String res = null;
        try {
            logger.info("getPriceAndMiles url:{},params:{}", subSystem.getUrl(), JSONObject.toJSONString(condition));
            res = HttpClientUtil.postJson(subSystem.getUrl(), null, JSONObject.toJSONString(condition), subSystem.getSocketTimeOut());
            logger.info("getPriceAndMiles url:{},result:{}", subSystem.getUrl(), res);
        } catch (Exception e) {
            logger.error("getPriceAndMiles 连接OTM 获取标准价连接超时 url:{},error:{}", subSystem.getUrl(), e);
            throw new BaseException("连接OTM  url:" + subSystem.getUrl() + "error:" + "获取标准价连接超时");
        }
        if (StringUtils.isNotBlank(res)) {
            JSONObject parseObject = JSONObject.parseObject(res);
            Boolean success = parseObject.getBoolean("success");
            if (success) {
                return parseObject.getJSONObject("data");
            } else {
                throw new BaseException(parseObject.getString("message"));
            }
        } else {
            throw new BaseException("OTM getPriceAndMiles未响应结果 url:" + subSystem.getUrl());
        }
    }

    /**
     * 回写结算价格到OTM
     */
    @Override
    public HashMap<String, String> exportPrice(Map<String, String> condition) {
        HashMap<String, String> params = Maps.newHashMap();
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        if (StringUtils.isBlank(condition.get("orderlineId"))) {
            throw new BaseException("订单号不能为空");
        }
        if (StringUtils.isBlank(condition.get("oilCost"))) {
            throw new BaseException("回写价格不能为空");
        }
        params.put("orderlineId", condition.get("orderlineId"));
        params.put("oilCost", condition.get("oilCost"));
        if (StringUtils.isNotBlank(condition.get("mileage"))) {
            params.put("kilometer", condition.get("mileage"));
        }
        //发送请求
        EntityWrapper<PushSubSystem> ew = new EntityWrapper<>();
        ew.eq("type", IntegrationURIEnum.EXPORT_PRICE.getCode())
                .orderBy("id", false);
        PushSubSystem subSystem = subSystemService.selectOne(ew);
        String res = null;
        HashMap<String, String> resultMap = Maps.newHashMap();
        try {
            String param = JSONObject.toJSONString(params);
            ExportLogHistory exportLogHistory = new ExportLogHistory();
            exportLogHistory.setTargertSys("OTM");
            exportLogHistory.setExportKey(params.get("orderlineId"));
            exportLogHistory.setType(IntegrationURIEnum.EXPORT_PRICE.getCode());
            exportLogHistory.setInterfaceUrl(subSystem.getUrl());
            exportLogHistory.setExportRemarks(IntegrationURIEnum.EXPORT_PRICE.getDetail());
            exportLogHistory.setExportStartTime(new Date());
            exportLogHistory.setExportEndTime(new Date());
            exportLogService.saveExportLogToQiniu(exportLogHistory, param);
            logger.info("exportPrice url:{},params:{}", subSystem.getUrl(), param);
            res = HttpClientUtil.postJson(subSystem.getUrl(), null, param, subSystem.getSocketTimeOut());
            logger.info("exportPrice url:{},result:{}", subSystem.getUrl(), res);
            if (StringUtils.isNotBlank(res)) {
                JSONObject parseObject = JSONObject.parseObject(res);
                Boolean success = parseObject.getBoolean("success");
                //更新结果-history
                EntityWrapper<ExportLogHistory> elhEW = new EntityWrapper<>();
                elhEW.eq("export_key", params.get("orderlineId"))
                        .eq("type", IntegrationURIEnum.EXPORT_PRICE.getCode());
                //更新结果-log
                EntityWrapper<ExportLog> elEW = new EntityWrapper<>();
                elEW.eq("targert_sys", "OTM")
                        .eq("export_key", params.get("orderlineId"))
                        .eq("type", IntegrationURIEnum.EXPORT_PRICE.getCode());
                if (success) {
                    ExportLogHistory resElh = new ExportLogHistory();
                    resElh.setExportStatus("success");
                    exportLogHistoryService.update(resElh, elhEW);
                    ExportLog exportLog = new ExportLog();
                    exportLog.setExportStatus("success");
                    exportLogService.update(exportLog, elEW);
                    resultMap.put("result", "true");
                } else {
                    String message = parseObject.getString("message");
                    ExportLogHistory resElh = new ExportLogHistory();
                    resElh.setExportStatus("false");
                    resElh.setExportRemarks(IntegrationURIEnum.EXPORT_PRICE.getDetail() + message);
                    exportLogHistoryService.update(resElh, elhEW);
                    resultMap.put("result", "false");
                    resultMap.put("message", message);
                }
            } else {
                resultMap.put("result", "false");
                resultMap.put("message", "OTM响应结果为空");
            }
        } catch (Exception e) {
            logger.error("exportPrice 回写结算价格到OTM连接超时 url:{},error:{}", subSystem.getUrl(), e);
            resultMap.put("result", "false");
            resultMap.put("message", "连接OTM超时");
        }
        return resultMap;
    }
}
